<?php
/**
 * @copyright   Copyright (c) 2017 https://www.sapixx.com All rights reserved.
 * @license     Licensed (http://www.apache.org/licenses/LICENSE-2.0).
 * @author      pillar<ltmn@qq.com>
 * 支付接口
 */
namespace app\allwin\controller\api\v4;
use app\allwin\controller\api\Base;
use app\allwin\model\AllwinShopOrder;
use app\common\facade\Inform;

class Shoporder extends Base{

    /**
     * 初始化当前应用是否登录
     * @return void
     */
    public function initialize() {
        parent::initialize();
        $this->isUserAuth();
    }


    /**
     * @param int $store_id
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 扫码店铺待核销订单列表
     */
    public function index(){
        $param['active']  = $this->request->param('active/d',0);
        $param['page']    = $this->request->param('page/d',1);
        $param['signkey'] = $this->request->param('signkey');
        $param['sign']    = $this->request->param('sign');
        $rel = $this->apiSign($param);
        if($rel['code'] != 200){
            return enjson($rel['code'],'签名验证失败');
        }
        $condition['user_id'] = $this->user->id;
        $condition['is_del']  = 0;
        switch ($param['active']) {
            case 1:
                $condition['paid_at'] = 0;
                break;
            case 2:
                $condition['paid_at'] = 1;
                $condition['status']  = 0;
                break;
            case 3:
                $condition['paid_at'] = 1;
                $condition['status']  = 1;
                break;
        }
        $order = AllwinShopOrder::with(['store'	=> function($query) {
            $query->field('name,address,id');
        }])->field('store_id,id,order_no,paid_at,paid_time,phone,points,message,shop_id,status,shop_cache,amount,create_time,is_del')->where($condition)->paginate(10);
        if($order->isEmpty()){
            return enjson(204);
        }
        $data = [];
        $ids  = [];
        foreach ($order as $key => $value) {
            $data[$key] = $value;
            $data[$key]['shop_cache'] = json_decode($value['shop_cache']);
            if($value['paid_at']){
                $data[$key]['status_text'] = $value['status']?'已核销':'待核销';
                $data[$key]['end_paytime'] = 0;
            }else{
                $data[$key]['status_text'] = '待支付';
                $data[$key]['end_paytime'] = (($value['create_time'] + 60 * 10) - time()) * 1000;
            }
            if($value['paid_at'] == 0 && $data[$key]['end_paytime'] < 0){
                $ids[] = $value['id'];
                unset($data[$key]);
            }
        }
        //过期了更改了状态
        if(!empty($ids)){
            AllwinShopOrder::where(['id' => $ids])->update(['is_del' => 1]);
        }
        if(empty($data)){
            return enjson(204);
        }
        return enjson(200,'成功',array_values($data));
    }

     /**
     * 统计订单
     */
    public function count(){
        $param['signkey'] = $this->request->param('signkey');
        $param['sign']    = $this->request->param('sign');
        $rel = $this->apiSign($param);
        if($rel['code'] != 200){
            return enjson($rel['code'],'签名验证失败');
        }
        $pending = AllwinShopOrder::where(['user_id' => $this->user->id,'is_del' => 0,'paid_at' => 0])->count();
        $order = AllwinShopOrder::where(['user_id' => $this->user->id,'is_del' => 0,'paid_at' => 1,'status' => 0])->count();
        return enjson(200,'成功',[$pending,$order]);
    }

        
    /**
     * @param int $store_id
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 扫码店铺待核销订单列表
     */
    public function getViews(){
        $param['id']      = $this->request->param('id/d',0);
        $param['signkey'] = $this->request->param('signkey');
        $param['sign']    = $this->request->param('sign');
        $rel = $this->apiSign($param);
        if($rel['code'] != 200){
            return enjson($rel['code'],'签名验证失败');
        }
        $condition['user_id'] = $this->user->id;
        $condition['id']      = $param['id'];
        $order = AllwinShopOrder::with(['store'	=> function($query) {
            $query->field('name,address,id,longitude,latitude');
        }])->field('store_id,id,order_no,paid_at,paid_time,phone,points,message,shop_id,status,shop_cache,amount,create_time,is_del')->where($condition)->find();
        if(empty($order)){
            return enjson(204);
        }
        $data = $order->toArray();
        $data['shop_cache'] = json_decode($order->shop_cache,true);
        $data['shop_cache']['notice'] = str_replace('<img', '<img class="img" style="max-width:100%;height:auto"',dehtml($data['shop_cache']['notice']));
        if($data['paid_at']){
            $data['end_paytime'] = 0;
        }else{
            $data['end_paytime'] = (($order->create_time + 60 * 10) - time()) * 1000;
        }
        if($order->paid_at == 0 && $data['end_paytime'] < 0){
            $order->is_del = 1;
            $order->save();
        }
        $data['distance']    = getDistance($this->qqgps['lng'],$this->qqgps['lat'],$order->store->longitude,$order->store->latitude);
        $data['paid_time']   = date('Y-m-d H:i:s',$order->paid_time);
        $data['create_time'] = date('Y-m-d H:i:s',$order->create_time);
        return enjson(200,'成功',$data);
    }

    /**
     * @param int $order_id
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * 获取核心订单
     */
    public function orderVer(){
        $param['id']      = $this->request->param('id/d',0);
        $param['signkey'] = $this->request->param('signkey');
        $param['sign']    = $this->request->param('sign');
        $rel = $this->apiSign($param);
        if($rel['code'] != 200){
            return enjson($rel['code'],'签名验证失败');
        }
        $condition['id'] = $param['id'];
        $condition['paid_at']            = 1;
        $condition['status']             = 0;
        $condition['is_del']             = 0;
        $info = AllwinShopOrder::with(['store'	=> function($query) {
            $query->field('name,address,id,longitude,latitude');
        }])->where($condition)->field('store_id,user_id,id,order_no,paid_at,paid_time,phone,points,message,shop_id,status,shop_cache,amount,create_time,is_del')->find();
        if(empty($info)){
            return enjson(303,'订单不存在',['url' => '/pages/index']);
        }
        $uid = [];
        if(!empty($info->storeWorker)){
            foreach ($info->storeWorker as $key => $value) {
                if($value['is_cashier'] == 1){
                    $uid[] = $value['uid'];
                }
            }
            $uid = array_flip($uid);
        }
        if (!isset($uid[$this->user->id])){
           return enjson(301,'你无权限核销订单',['url' => '/pages/store/views?store_id='.$info->store_id]);
        }
        if(request()->isPost()){
            Inform::sms($info->user_id,$this->miniapp_id,['title' =>'['.$info->store->name.']订单已核销','type' => '核销通知','state'=>'成功','content' =>'单号:'.$info->order_no,'url' => 'pages/index']);
            Inform::sms($info->user->id,$this->miniapp_id,['title' =>'你成功核销一个订单','type' => '核销通知','state'=>'成功','content' =>'单号:'.$info->order_no,'url' => 'pages/index']);
            $info->status = 1;
            $info->save();
            return enjson(301,'订单成功核销',['url' => '/pages/store/views?store_id='.$info->store_id]);
        }else{
            $shop_cache= json_decode($info->shop_cache,true);
            $shop_cache['notice'] = dehtml($shop_cache['notice']);
            $info->shop_cache = $shop_cache;
            $info->paid_time   = date('Y-m-d H:i:s',$info->paid_time);
            $info->create_time = date('Y-m-d H:i:s',$info->create_time);
            return enjson(200,'成功',$info);
        }
    }
}